package com.unittec.zk.provider.work.service;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.unittec.zk.provider.scope.ThreadLocalScope;
import com.unittec.zk.provider.scope.ThreadLocalScopeCache;
import com.unittec.zk.provider.utils.CopyUtils;
import com.unittec.zk.provider.utils.UUIDUtils;
import com.unittec.zk.provider.work.entity.Attachment;
import com.unittec.zk.provider.work.entity.WorkPlanJoin;
import com.unittec.zk.provider.work.entity.WorkPlanRecords;
import com.unittec.zk.provider.work.mapper.AttachmentMapper;
import com.unittec.zk.sdk.root.internal.exception.BusinessException;
import com.unittec.zk.sdk.work.domain.AttachmentDTO;
import com.unittec.zk.sdk.work.request.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.xml.ws.Action;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.unittec.zk.provider.work.mapper.WorkPlanMapper;
import com.unittec.zk.provider.work.entity.WorkPlan;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

@Service
@Transactional
public class WorkPlanService extends ServiceImpl<WorkPlanMapper, WorkPlan> {

    @Resource
    private WorkPlanJoinService workPlanJoinService;

    @Resource
    private WorkPlanRecordsService workPlanRecordsService;

    @Resource
    private AttachmentService attachmentService;

    @Autowired
    private WorkPlanRecordsService recordsService;
    @Autowired
    private WorkPlanMapper workPlanMapper;
    @Autowired
    private AttachmentMapper attachmentMapper;



    /**
     * 工作计划-增/改
     *
     * @param req202015
     * @return
     */
    public Object saveOrUpdateWorkplan(Req202015 req202015) {
        WorkPlan workPlan = new WorkPlan();
        CopyUtils.copyProperties(req202015, workPlan);
        //判断是增还是改
        if (StrUtil.isBlank(workPlan.getId())) {
            workPlan.setId(UUIDUtils.getId());
        }
        //判断该工作计划是否审批成功，成功的不能改
        else {
            WorkPlan byId = this.getById(req202015.getId());
            if (byId!=null && "1".equals(byId.getIsApproveSuccess())) {
                throw new BusinessException("该工作计划已经审批成功，不能修改");
            }
        }
        //1、存工作计划
        this.saveOrUpdate(workPlan);
        //2、删关联参与人
        LambdaQueryWrapper<WorkPlanJoin> qw1 = new LambdaQueryWrapper<>();
        qw1.eq(WorkPlanJoin::getRelationPlanId, workPlan.getId());
        workPlanJoinService.remove(qw1);
        //3、删关联附件表
        LambdaQueryWrapper<Attachment> qw = new LambdaQueryWrapper<>();
        qw.eq(Attachment::getRelationId, workPlan.getId());
        attachmentService.remove(qw);
        //4、增关联参与人
        ArrayList<WorkPlanJoin> workPlanJoins = new ArrayList<>();
        req202015.getJoinnerIds().forEach(x -> {
            WorkPlanJoin workPlanJoin = new WorkPlanJoin();
            workPlanJoin.setUserId(x);
            workPlanJoin.setRelationPlanId(workPlan.getId());
            workPlanJoins.add(workPlanJoin);
        });
        //把 leader也加到参与人表中
        WorkPlanJoin workPlanJoin = new WorkPlanJoin();
        workPlanJoin.setUserId(workPlan.getLeaderId());
        workPlanJoin.setRelationPlanId(workPlan.getId());
        workPlanJoins.add(workPlanJoin);
        workPlanJoinService.saveBatch(workPlanJoins);
        //5、增关联附件表
        ArrayList<Attachment> attachments = new ArrayList<>();
        req202015.getFileDtoList().forEach(x -> {
            Attachment attachment = new Attachment();
            attachment.setFileName(x.getFileName());
            attachment.setFilePath(x.getFilePath());
            attachment.setFileSize(x.getFileSize());
            attachment.setRelationId(workPlan.getId());
            attachments.add(attachment);
        });
        attachmentService.saveBatch(attachments);
        return "Success";
    }

    /**
     * 工作计划-我创建的-分页
     *
     * @param req202016
     * @return
     */
    public Object getWorkplanPage(Req202016 req202016) {
        LambdaQueryWrapper<WorkPlan> qw = new LambdaQueryWrapper<>();
        if (StrUtil.isNotBlank(req202016.getPlanName())) {
            qw.like(WorkPlan::getPlanName, req202016.getPlanName());
        }
        if (StrUtil.isNotBlank(req202016.getIsApproveSuccess())) {
            qw.eq(WorkPlan::getIsApproveSuccess, req202016.getIsApproveSuccess());
        }
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        if (req202016.getTimeStart() != null) {
            qw.ge(WorkPlan::getCreateTime, df.format(req202016.getTimeStart()));
        }
        if (req202016.getTimeEnd() != null) {
            qw.le(WorkPlan::getCreateTime, df.format(req202016.getTimeEnd()) + " 24:00:00");
        }
        //查找 我的
        qw.eq(WorkPlan::getCreateUser, ThreadLocalScope.getAuthData().getUser());
        Page<Map<String, Object>> page = this.baseMapper.getWorkPlanPage(new Page<>(req202016.getCurrent(), req202016.getSize()), qw);
        return page;
    }

    /**
     * 工作计划-删除
     *
     * @param req202017
     * @return
     */
    public Object delWorkplan(Req202017 req202017) {
        //1、删工作计划
        this.removeByIds(req202017.getIds());
        //2、删参与人
        workPlanJoinService.remove(new LambdaQueryWrapper<WorkPlanJoin>().in(WorkPlanJoin::getRelationPlanId, req202017.getIds()));
        //3、找出相关汇报id，删汇报
        List<WorkPlanRecords> list = workPlanRecordsService.list(new LambdaQueryWrapper<WorkPlanRecords>().in(WorkPlanRecords::getRelationId, req202017.getIds()));
        List<String> attachmentRIds = new ArrayList<>();
        list.forEach(x -> {
            attachmentRIds.add(x.getId());
        });
        workPlanRecordsService.remove(new LambdaQueryWrapper<WorkPlanRecords>().in(WorkPlanRecords::getRelationId, req202017.getIds()));
        //4、根据工作计划,汇报，删对应的附件
        attachmentRIds.addAll(req202017.getIds());
        attachmentService.remove(new LambdaQueryWrapper<Attachment>().in(Attachment::getRelationId, attachmentRIds));
        return "Success";
    }

    /**
     * 工作计划-我创建的-详情
     *
     * @param req202018
     * @return
     */
    public Object getDetails1(Req202018 req202018) {
        Map<String, Object> rs = this.baseMapper.getDetails1(req202018.getId());
        List<Attachment> list = attachmentService.list(new LambdaQueryWrapper<Attachment>().eq(Attachment::getRelationId, req202018.getId()));
        rs.put("attachment_list", list);
        return rs;
    }

    /**
     * 工作计划-我参与的-分页
     * @param req202019
     * @return
     */
    public Object getMyWorkPlanPage(Req202019 req202019) {
        String now = new SimpleDateFormat("yyyy-MM-dd").format(new Date(System.currentTimeMillis()));
        Page<Object> pagemodel = new Page<>(req202019.getCurrent(), req202019.getSize());
        Page<Map<String,Object>> page = this.baseMapper.getMyWorkPage(pagemodel,
                req202019.getPlanName(),
                req202019.getState(),
                now,
                ThreadLocalScope.getAuthData().getUser());
        return page;
    }
    /**工作计划-我参与的-详情-工作进展
     *
     * @param req202021
     * @return
     */

    public Object getMyWorkProgress(Req202021 req202021) {
        String id = req202021.getId();
        if (!StringUtils.isEmpty(id)){
            //查出对应relation_id 的work_plan_records
            List<WorkPlanRecords> workPlanRecords = recordsService.list(new QueryWrapper<WorkPlanRecords>().eq("relation_id", id).eq("records_type",2));
            List<Map<String, Object>> collect1 = workPlanRecords.stream().map(w -> {
                //当前内容
                String content = w.getContent();
                //通过记录id查到附件表 attachment
                List<Attachment> attachments = attachmentService.list(new QueryWrapper<Attachment>().eq("relation_id", w.getId()));
                List<AttachmentDTO> collect = attachments.stream().map(attachment -> {
                    AttachmentDTO attachmentDTO = new AttachmentDTO();
                    BeanUtils.copyProperties(attachment, attachmentDTO);
                    return attachmentDTO;
                }).collect(Collectors.toList());
                Map<String, Object> map = new HashMap<>();
                //创建用户
                String user = workPlanMapper.getUserById(w.getCreateUser());
                //创建时间
                Date createTime = w.getCreateTime();
                map.put("content", content);
                map.put("file", collect);
                map.put("user_name", user);
                map.put("create_time", createTime);
                return map;
            }).collect(Collectors.toList());
            return collect1;
        }
        return null;

    }
}
